package com.lyy.photovoltaic.service.impl;

import com.lyy.photovoltaic.beans.Users;
import com.lyy.photovoltaic.beans.UsersEquipmentsLists;
import com.lyy.photovoltaic.beans.UsersInfo;
import com.lyy.photovoltaic.common.utils.MyMD5Util;
import com.lyy.photovoltaic.common.utils.MyRandom;
import com.lyy.photovoltaic.common.vo.ResultCode;
import com.lyy.photovoltaic.common.vo.ResultVO;
import com.lyy.photovoltaic.mapper.UsersEquipmentsListsMapper;
import com.lyy.photovoltaic.mapper.UsersInfoMapper;
import com.lyy.photovoltaic.mapper.UsersMapper;
import com.lyy.photovoltaic.service.UserService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UsersInfoMapper usersInfoMapper;
    @Autowired
    UsersEquipmentsListsMapper usersEquipmentsListsMapper;
    @Override
    public ResultVO checkLogin(String uId, String pwd) {

        boolean flag = false;
        //1.根据账号名查询用户信息
        Users user = usersMapper.selectByPrimaryKey(uId);
        //2.判断
        if (user != null) {
            try {
                flag = MyMD5Util.validPassword(pwd, user.getUserPassword());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println(flag);
            if (flag) {
                //如果登录验证成功，则需要生成token
                //使用jwt生成token字符串
                JwtBuilder builder = Jwts.builder();
                String token = builder.setSubject(user.getUserId())        //jwt第二部分data
                        .setIssuedAt(new Date())                   //设置token的生成时间
                        .setId(user.getUserId())
                        .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))//设置token过期时间。一天
                        .signWith(SignatureAlgorithm.HS256, "fasdfkjnior342f3")
                        .compact();//设置加密方式及密码
                ResultVO resultVO = new ResultVO(ResultCode.LOGIN_SUCCESS_USER, token, user);
                //System.out.println(resultVO);
                return resultVO;
            }
        }
        return new ResultVO(ResultCode.LOGIN_FAILED, null);
    }


    @Transactional
    public ResultVO userRegist(String uId, String pwd) {
        synchronized (this) {
//            System.out.println(uId + "-------" + pwd);
            //1.查询用户账号是否已经被注册
            Users user = usersMapper.selectByPrimaryKey(uId);
            //2.如果没有被注册则进行保存
            if (user == null) {
                try {
                    String md5pwd = MyMD5Util.getEncryptedPwd(pwd);
                    Users user2 = new Users();
                    user2.setUserId(uId);
                    user2.setUserPassword(md5pwd);
                    int i = usersMapper.insert(user2);

                    String uelId = System.currentTimeMillis() + MyRandom.getStringRandom() + uId;
                    UsersInfo userInfo = new UsersInfo();
                    userInfo.setUserInfoId(uId);
                    userInfo.setUserId(uId);
                    userInfo.setUserCreatetime(new Date());
                    userInfo.setUelId(uelId);
                    int u = usersInfoMapper.insert(userInfo);
                    UsersEquipmentsLists usersEquipmentsList = new UsersEquipmentsLists();
                    usersEquipmentsList.setUelId(uelId);
                    usersEquipmentsList.setUserId(uId);
                    System.out.println(usersEquipmentsList);
                    int i1 = usersEquipmentsListsMapper.insert(usersEquipmentsList);
                    System.out.println(i1);
//                    System.out.println(u);
//                    System.out.println(i);
                    if (i > 0) {
                        return new ResultVO(ResultCode.REGIST_SUCCESS, user2);
                    } else {
                        //return new ResultVO(10002, "注册失败", null);
                        return new ResultVO(ResultCode.REGIST_FAILED_USER, null);

                    }
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            //System.out.println("23123");
            return new ResultVO(ResultCode.REGIST_FAILED, null);
        }
    }

    @Override
    public ResultVO updatePassword(String uId, String originPwd, String newPwd) {
//        System.out.println("uId:"+uId+"originPwd:"+originPwd+"newPwd:"+newPwd);
        boolean flag = false;
        //1.根据账号名查询用户信息
        Users user = usersMapper.selectByPrimaryKey(uId);
        //2.判断
        if (user != null) {
            try {
                flag = MyMD5Util.validPassword(originPwd, user.getUserPassword());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println(flag);
            if (flag) {
                System.out.println(user);
                //如果密码验证成功，则需要修改原密码，并生成新token
                try {
                    String encryptedPwd = MyMD5Util.getEncryptedPwd(newPwd);
                    user.setUserPassword(encryptedPwd);
                    int i = usersMapper.updateByPrimaryKeySelective(user);
                    if (i > 0) {
                        ResultVO resultVO = new ResultVO(ResultCode.LOGIN_SUCCESS_USER, "修改密码成功", user);
                        return resultVO;
                    }
                    System.out.println(user);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return new ResultVO(ResultCode.FAILED,"修改密码失败", null);
    }


}
